<?php
namespace app\api\services;

use app\common\libs\Singleton;

class ExpressService
{
    use Singleton;

    public function getExpress($expressNo)
    {
        return $this->curl($expressNo);
    }

    /**
     * 订单号物流信息查询
     *
     * @param  string  $param.expressNo
     * @param  string  $param.expressCode
     * @return [type]        [description]
     */
    public function query(array $param)
    {
        $type = env('app.EXP_TYPE');
        // var_dump($type);exit;
        if ($type == 'kuaidi100') {
            return $this->kuaidi100Query($param);
        } else {
        }
    }

    /**
     * https://api.kuaidi100.com/document/5f0ffb5ebc8da837cbd8aefc
     * https://github.com/kuaidi100-api/php-demo
     * @param  array $param [description]
     * @return [type]            [description]
     */
    public function kuaidi100Query($param)
    {
        //参数设置
        $key      = env('app.kuaidi100_key'); // 客户授权key
        $customer = env('app.kuaidi100_customer'); //查询公司编号
        $param    = [
            'com'      => $param['expressCode'] ?? '', // 快递公司编码
            'num'      => $param['expressNo'], // 快递单号
            'phone'    => '', // 手机号
            'from'     => '', // 出发地城市
            'to'       => '', // 目的地城市
            'resultv2' => '1', // 开启行政区域解析
            'show'     => '0', // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order'    => 'desc', // 返回结果排序:desc降序（默认）,asc 升序
        ];

        //请求参数
        $post_data             = [];
        $post_data['customer'] = $customer;
        $post_data['param']    = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sign                  = md5($post_data['param'] . $key . $post_data['customer']);
        $post_data['sign']     = strtoupper($sign);

        $url = 'https://poll.kuaidi100.com/poll/query.do'; // 实时查询请求地址

        // echo '请求参数：<br/><pre>';
        // echo print_r($post_data);
        // echo '</pre>';

        // 发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        // 第二个参数为true，表示格式化输出json
        $data = json_decode($result, true);
        /*
        {
            "message": "ok",
            "nu": "xxx",
            "ischeck": "1",
            "com": "jd",
            "status": "200",
            "data":[],
            "state": "3",
            "condition": "F00"
        }
        array(3) {
          ["result"]=>
          bool(false)
          ["returnCode"]=>
          string(3) "401"
          ["message"]=>
          string(24) "不支持此快递公司"
        }
        */
        // echo '<br/><br/>返回数据：<br/><pre>';
        // echo print_r($data);
        // var_dump($data);
        // echo '</pre>';exit;
        return $data;
    }

    /**
     * https://startup.aliyun.com/city/vanke-wanchuang/portal/services/1255374520630382594.html
     * @param  [type] $expressNo [description]
     * @return [type]            [description]
     */
    public function curl($expressNo)
    {
        error_reporting(E_ALL || ~E_NOTICE);
        $host    = "https://wuliu.market.alicloudapi.com"; //api访问链接
        $path    = "/kdi"; //API访问后缀
        $method  = "GET";
        $appcode = "db9c3eb58fb14d789c90f2e7b0da72cd"; //开通服务后 买家中心-查看AppCode
        $headers = [];
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $query = "no=" . $expressNo; //参数写在这里
        //        $bodys = "";
        $url = $host . $path . "?" . $query;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            $body = json_decode($body, true);
            if ($body['status'] != 0) {
                return [];
            } else {
                return $body['result']['list'];
            }
        } else {
            if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                print("参数错误");
            } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                print("AppCode错误");
            } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                print("请求的 Method、Path 或者环境错误");
            } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                print("服务未被授权（或URL和Path不正确）");
            } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                print("套餐包次数用完");
            } elseif ($httpCode == 403 && strpos($header, "Api Market Subscription quota exhausted") !== false) {
                print("套餐包次数用完，请续购套餐");
            } elseif ($httpCode == 500) {
                print("API网关错误");
            } elseif ($httpCode == 0) {
                print("URL错误");
            } else {
                print("参数名错误 或 其他错误");
                print($httpCode);
                $headers  = explode("\r\n", $header);
                $headList = [];
                foreach ($headers as $head) {
                    $value               = explode(':', $head);
                    $headList[$value[0]] = $value[1];
                }
                print($headList['x-ca-error-message']);
            }
        }
    }
}
